Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
Why a simple `useEffect` is not taking updated value when it is warping any "setInterval/timeout" inside

Why a simple useEffect is not taking updated value when it is warping any setInterval/timeout inside;

Code sandbox

where variable stopped to initial value;

import { useState, useEffect } from "react";
let timerRef;
const StopWatch = () => {
  const [time, setTime] = useState(0);
  const [isPause, setPause] = useState(false);
  useEffect(() => {
    timerRef = setInterval(() => {
      console.log({ time });
      if (!isPause) {
        setTime(time + 1);
      }
    }, 5000);
    return () => clearInterval(timerRef);
  }, []);
  const startWatch = () => {
    setPause(false);
  };
  const stopWatch = () => {
    setPause(true);
  };
  return (
    <>
      time: {time}
      <button onClick={startWatch}>Start</button>
      <button onClick={stopWatch}>stop</button>
    </>
  );
};
export { StopWatch };

output

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

pass dependency of time and this should work

useEffect(() => {
    let _time = time;
    console.log({ time });
    timerRef = setInterval(() => {
      console.log({ _time });
      if (!isPause) {
        setTime(_time + 1);
      }
    }, 5000);
    return () => clearInterval(timerRef);
  }, [time]);
about 4 years ago · Juan Pablo Isaza Report

0

That is because you are accessing time value from the closure, and since you are defining setTimeout handler only once (on initialization) then it will always refer to that initial value for time. I suggest, for this use case, just to use state updater with callback, and like that it will provide you mechanism to easily update state with previos one, and by not accessing state directly. Just rewrite setTime(_time + 1) to setTime(prevTime => prevTime + 1)

about 4 years ago · Juan Pablo Isaza Report

0

CodeSandbox already warned you about that.

enter image description here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!